import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:get/get.dart';
import 'package:kq_flutter_core_widget/config/kq_core_global.dart';
import 'package:kq_flutter_core_widget/resources/l10n/kq_core_s.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_widgets/config/kq_global.dart';
import 'package:kq_flutter_core_widget/utils/event_bus_utils.dart';
import 'package:kq_flutter_widgets/resources/l10n/kq_intl.dart';
import 'package:kq_flutter_widgets_example/event/theme_change_event.dart';
import 'package:kq_flutter_widgets_example/pages/home/homePage/view.dart';
import 'package:kq_flutter_widgets_example/resources/l10n/l10n.dart';
import 'package:kq_flutter_widgets_example/router/route_map.dart';
import 'package:kq_flutter_widgets_example/utils/kq_style_util.dart';

import 'config/global.dart';
import 'event/locale_change_event.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  //公共函数初始化后再初始化app
  KqCoreGlobal.init().then((value) => runApp(const MyApp()));
}

/// 程序入口
class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  Locale? _locale;

  @override
  void initState() {
    _initTheme();
    EventBusUtils.global.on<ThemeChangeEvent>().listen((event) {
      print('111');
      setState(() {
        _initTheme();
      });
    });
    super.initState();
    _initLocale();
    EventBusUtils.global.on<LocaleChangeEvent>().listen((event) {
      setState(() {
        _initLocale();
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    EventBusUtils.global.destroy();
  }

  /// 初始化当前语言
  void _initLocale() async {
    // var language = await SpfUtil.getLanguage();
    var language = languageZh;
    if (languageEn == language) {
      _locale = const Locale(languageEn);
    } else {
      _locale = const Locale(languageZh);
    }
  }

  void _initTheme() async {
    var configId = KqCoreGlobal.prefs!.getString('theme') ?? Global.themeYellow;
    KqGlobal.themeConfigId = configId;
  }

  @override
  Widget build(BuildContext context) {
    return KqScreenUtilInit(
      //初始化屏幕适配框架
      designSize: const Size(414, 736),
      minTextAdapt: true,
      builder: _buildApp,
      child: const HomePage(),
    );
  }

  void _initWithContext(BuildContext context) {
    // 主题配置
    KqStyleUtil.themeData();
    S.load(context);
    EasyRefresh.defaultHeaderBuilder = () => const MaterialHeader();
  }

  Widget _buildApp(BuildContext context, Widget? child) {
    return GetMaterialApp(
      title: '小诸葛组件库',
      navigatorKey: KqCoreGlobal.navigatorKey,
      defaultTransition: Transition.rightToLeft,
      getPages: RouteMap.getPages,
      navigatorObservers: [PageRouteObserver._pageRouteObserver._routeObserver],
      localizationsDelegates: [
        ...S.localizationsDelegates,
        KqCoreLocalizationDelegate.delegate,
        KqLocalizationDelegate.delegate,
      ],
      supportedLocales: S.supportedLocales,
      //国际化语言配置文件
      locale: _locale,
      //设置默认语言
      fallbackLocale: const Locale(languageZh),
      //配置错误的情况，使用的语言
      theme: ThemeData(
        useMaterial3: false,
        primarySwatch: Colors.blue,
      ),
      home: child,
      builder: (context, child) {
        _initWithContext(context);
        return EasyLoading.init()(context, child);
      },
    );
  }
}

/// 页面路由监听
///
/// 可监听当前界面显示还是隐藏，从导航加载及移出导航
class PageRouteObserver {
  /// 路由监听器
  final RouteObserver<PageRoute> _routeObserver = RouteObserver<PageRoute>();

  static final PageRouteObserver _pageRouteObserver =
      PageRouteObserver._internal();

  PageRouteObserver._internal();

  /// 注册页面路由监听
  ///
  /// [context]为页面上下文，通过此上下文找到当前页面路由，如果无法找到，则不会注册。
  /// 而且只支持页面路由的注册，弹窗类路由不支持
  static void subscribe(RouteAware routeAware, BuildContext context) {
    var route = ModalRoute.of(context);
    if (route is PageRoute) {
      _pageRouteObserver._routeObserver.subscribe(routeAware, route);
    }
  }

  /// 移除页面路由监听
  static void unsubscribe(RouteAware routeAware) {
    _pageRouteObserver._routeObserver.unsubscribe(routeAware);
  }
}
